﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Core.DynamicForm.OperationWebService;
using Kingdee.BOS.Core.DynamicService;
using Kingdee.BOS.DataEntity.Metadata.Service;
using System.Windows.Forms;
using Kingdee.BOS.Util;
using System.ComponentModel;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json.Linq;
using Kingdee.K3.FIN.Core.Object.IV.GoldenTax.TaxManagementSystem;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Authentication;
using Kingdee.BOS.Log;
using System.Security.Policy;
using Kingdee.BOS.BusinessEntity.BusinessFlow;


namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 接收银行交易明细单据操作插件
    /// </summary>
    /// <remarks>
    /// 功能：接收银行交易明细单据选择数据行，点击生成按钮，生成待认领清单
    /// 创建人：wzx
    /// 创建日期：2024.4.25
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [Description("接收银行交易明细单据同步生成待认领清单")]
    [HotUpdate]
    public class RecBankTradeDetailService : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            #region 基本信息——文本字段
            //银企流水号
            e.FieldKeys.Add("FSETTLENO");
            //交易时间
            e.FieldKeys.Add("FTRANSDATE");
            //银行账号
            e.FieldKeys.Add("FBANKACNTNO");
            //账户名称
            e.FieldKeys.Add("FBANKACNTNAME");
            //开户银行
            e.FieldKeys.Add("FOpenBankName");
            //对方账号
            e.FieldKeys.Add("FOppBankAcntNo");
            //对方账户名称
            e.FieldKeys.Add("FOppBankAcntName");
            //对方开户行
            e.FieldKeys.Add("FOppOpenBankName");
            //到账日期
            e.FieldKeys.Add("FTOACCOUNTDATE");
            //贷方/收款金额
            e.FieldKeys.Add("FCREDITAMOUNT");
            //币别
            e.FieldKeys.Add("FCurrency");
            //摘要
            e.FieldKeys.Add("FEXPLANATION");
            //借方/付款金额
            e.FieldKeys.Add("FDEBITAMOUNT");
            //业务参考号
            e.FieldKeys.Add("FBUSIREFENO");
            #endregion

            #region 其他信息
            //收付组织
            e.FieldKeys.Add("FPAYORGID");
            //结算组织
            e.FieldKeys.Add("FSETTLEORGID");
            //业务类型
            e.FieldKeys.Add("FBUSINESSTYPE");
            //对方单位
            e.FieldKeys.Add("FPAYUNIT");
            //接收单据编号
            e.FieldKeys.Add("FRecBillNo");
            //对方单位类型
            e.FieldKeys.Add("FPAYUNITTYPE");
            //结算方式
            e.FieldKeys.Add("FSETTLETYPEID");
            //收付款用途
            e.FieldKeys.Add("FPURPOSEID");
            //业务标记
            e.FieldKeys.Add("FTransType");
            //结算方式
            e.FieldKeys.Add("FSettleTypeID");
            //退款流水号
            e.FieldKeys.Add("FREFUNDNO");
            //银行流水号
            e.FieldKeys.Add("FBNKSEQNO");
            //对方联行号
            e.FieldKeys.Add("FOppOpenBankNo");
            //银企付款
            e.FieldKeys.Add("FISBANKPAY");
            //银行代扣
            e.FieldKeys.Add("FisBankcharge");
            //子账户类型
            e.FieldKeys.Add("FSUBACCOUNTTYPE");
            //子账户号
            e.FieldKeys.Add("FSUBACCOUNT");
            //余额
            e.FieldKeys.Add("FBALANCEAMOUNT");
            //单据编号
            e.FieldKeys.Add("FBillNo");
            //银行交易流水号
            e.FieldKeys.Add("FBANKTRANSNO");
            //币别内码
            e.FieldKeys.Add("FCurrencyId");
            //银行账号内码
            e.FieldKeys.Add("FACCOUNTID");
            //会计流水号
            e.FieldKeys.Add("FACCOUNTINGSERIALNO");
            //销售组织
            e.FieldKeys.Add("FSALEORGID");
            //已生成待认领清单
            e.FieldKeys.Add("F_RDLV_GenerateStatus");

            #endregion

        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);

            foreach (DynamicObject entity in e.DataEntitys)
            {
                string UserName = this.Context.UserName;
                string FID= Convert.ToString(entity["ID"]);//内码
                string SETTLENO = Convert.ToString(entity["FSETTLENO"]);//银企流水号
                string BNKSEQNO = Convert.ToString(entity["FBNKSEQNO"]);//银行流水号
                string TRANSDATE = Convert.ToString(entity["FTRANSDATE"]);//交易日期
                
                DynamicObject PAYORG = entity["FPAYORGID"] as DynamicObject;//收付组织   
                string PAYORGNO = "";
                if (PAYORG!=null)
                {
                    PAYORGNO = PAYORG["Number"].ToString();
                }
                decimal CREDITAMOUNT = 0;
                CREDITAMOUNT = Convert.ToDecimal(entity["FCREDITAMOUNT"]);//贷方-收款金额
                DynamicObject ACCOUNT = entity["FACCOUNTID"] as DynamicObject;//收款银行账号 
                string ACCOUNTNO = "";
                if (ACCOUNT != null)
                {
                    ACCOUNTNO = ACCOUNT["Number"].ToString();
                }
                DynamicObject PAYUNIT = entity["FPAYUNIT"] as DynamicObject;//结算方式 
                string PAYUNITNO = "";
                if (PAYUNIT != null)
                {
                    PAYUNITNO = PAYUNIT["Number"].ToString();
                }
                DynamicObject Currency = entity["FCurrencyId"] as DynamicObject;//币别 
                string CurrencyNO = "";
                if (Currency != null)
                {
                    CurrencyNO = Currency["Number"].ToString();
                }
                string OppBankAcntName = Convert.ToString(entity["FOppBankAcntName"]);//对方账户名称
                string OppBankAcntNo = Convert.ToString(entity["FOppBankAcntNo"]);//对方银行账号
                string OppOpenBankName = Convert.ToString(entity["FOppOpenBankName"]);//对方开户行
                string F_RDLV_GenerateStatus = Convert.ToString(entity["F_RDLV_GenerateStatus"]);//已生成待认领清单
                //未生成待认领清单数据且是收款的明细
                if (F_RDLV_GenerateStatus!="True" && CREDITAMOUNT>0 && OppBankAcntName != "利民控股集团股份有限公司"
                     && OppBankAcntName != "利民化学有限责任公司" && OppBankAcntName != "河北威远生物化工有限公司"
                     && OppBankAcntName != "内蒙古新威远生物化工有限公司" && OppBankAcntName != "河北双吉化工有限公司"
                     && OppBankAcntName != "中国证券登记结算有限责任公司深圳分公司")
                {
                    K3CloudApiClient client = new K3CloudApiClient("http://10.10.11.100/K3Cloud/");
                    string loginResult = client.LoginByAppSecret(
                    "6642ecc879eb25",//账套
                    UserName,//用户名
                    "278414_Q/dDxcEL5MmaR/8p453Dy99EQq3bToLG",//应用ID
                    "ccecc8d0a50d4fdcb51e2684ee906248",//应用秘钥
                    2052 //中文
                    );

                    //K3CloudApiClient client = new K3CloudApiClient("http://10.10.11.100/K3Cloud/");
                    //string loginResult = client.LoginByAppSecret(
                    //"6642ed2979eb27",//账套
                    //UserName,//用户名
                    //"275093_530rSyEIVlC4wX1K73QK1YUN3Jx9RttP",//应用ID
                    //"9a284d57df6a441ea6551734f0ea0120",//应用秘钥
                    //2052 //中文
                    //);

                    Newtonsoft.Json.Linq.JObject loginResultObj = JObject.Parse(loginResult);

                    JToken loginResultType;

                    loginResultObj.TryGetValue("LoginResultType", out loginResultType);
                    var context = this.Context;
                    if (loginResultType != null && loginResultType.Value<Int32>() == 1)
                    {
                        #region JSON
                        // 获取保存Json
                        var saveStr = BuildUploadObj(context);
                        // 转成JObject
                        JObject saveObj = JObject.Parse(saveStr);
                        //删除不需要传值的字段
                        JObject JO= (JObject)saveObj["Model"];
                        JO.Remove("F_QLTK_ExchangeRate");//汇率
                        JO.Remove("F_DEV_FDATE");//同步CRM日期
                        // 获取Model
                        JToken modelObj = JO;
                        // 设值
                        JObject basedata = new JObject();
                        basedata.Add("FNumber", PAYORGNO);
                        modelObj["F_RDLV_OrgId_83g"] = basedata;//组织
                        modelObj["F_RDLV_SerialNumber"] = BNKSEQNO;//流水号
                        modelObj["F_RDLV_TradingDay"] = TRANSDATE;//交易日
                        modelObj["F_RDLV_Amount"] = CREDITAMOUNT;//交易金额
                        basedata = new JObject();
                        basedata.Add("FNumber", ACCOUNTNO);
                        modelObj["F_RDLV_Base_w5c"] = basedata;//收款银行账号
                        basedata = new JObject();
                        basedata.Add("FNumber", "JSFS04_SYS");
                        modelObj["F_RDLV_SettleType"] = basedata;//结算方式
                        basedata = new JObject();
                        basedata.Add("FNumber", CurrencyNO);
                        modelObj["F_RDLV_CurrencyType"] = basedata;//币别
                        modelObj["F_RDLV_PayerAccount"] = OppBankAcntName;//付款方账户名称
                        modelObj["F_RDLV_PayerBankAccount"] = OppBankAcntNo;//付款方银行账号
                        modelObj["F_RDLV_PayerOpenBank"] = OppOpenBankName;//付款方开户行
                        modelObj["F_RDLV_CDQFR"] = "";//承兑签发日
                        modelObj["F_RDLV_CDDQR"] = "";//承兑到期日

                        basedata = new JObject();
                        basedata.Add("FNumber", "CNY");
                        modelObj["F_QLTK_BaseCurrency"] = basedata;//本位币
                        basedata = new JObject();
                        basedata.Add("FNumber", "HLTX01_SYS");
                        modelObj["F_QLTK_Exchange"] = basedata;//汇率类型
                        


                        #endregion
                        var R=client.Save("RDLV_PendingCollectionList",Convert.ToString(saveObj));
                        Common.ResultObject resultObject = JsonConvert.DeserializeObject<Common.ResultObject>(R);
                        string IsSuccess = resultObject.result.responseStatus.IsSuccess;
                        string RNumber= resultObject.result.number.ToString();
                        string ErrorMessage = "";
                        if (resultObject.result.responseStatus.Errors.Length > 0)
                        {
                            for (int i = 0; i< resultObject.result.responseStatus.Errors.Length; i++)
                            {
                                ErrorMessage = ErrorMessage + "(" + i.ToString() + ")" + resultObject.result.responseStatus.Errors[i].FieldName + resultObject.result.responseStatus.Errors[i].Message + ";\t";
                            }
                        }
                        bool bIsSuccess = Convert.ToBoolean(IsSuccess);
                        if (bIsSuccess)//如果保存成功
                        {
                            IOperationResult operationResult = new OperationResult();
                            operationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = true,
                                Message = string.Format("生成待认领清单成功,单据编码为：{0}", RNumber),
                                MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.Warning,
                                PKValue = 0,
                            });
                            this.OperationResult.MergeResult(operationResult);
                            string SQL= string.Format(@"update  T_CN_BANKCASHFLOW set F_RDLV_GenerateStatus=1 where FID='{0}'", FID);
                            DBUtils.Execute(context, SQL);
                        }
                        else
                        {
                            IOperationResult operationResult = new OperationResult();
                            operationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = false,
                                Message = string.Format("生成待认领清单失败！原因：{0}", ErrorMessage),
                                MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.Warning,
                                PKValue = 0,
                            });
                            this.OperationResult.MergeResult(operationResult);
                            string SQL = string.Format(@"update  T_CN_BANKCASHFLOW set F_RDLV_GenerateStatus=0 where FID='{0}'", FID);
                            DBUtils.Execute(context, SQL);
                        }
                    }
                    else//登陆失败
                    {
                        IOperationResult operationResult = new OperationResult();
                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = false,
                            Message = string.Format("登录失败！原因：{0}", Enum.GetName(typeof(Common.LogResult), loginResultType.Value<Int32>())),
                            MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);
                        string SQL = string.Format(@"update  T_CN_BANKCASHFLOW set F_RDLV_GenerateStatus=0 where FID='{0}'", FID);
                        DBUtils.Execute(context, SQL);
                    }
                }
            }           
        }


        // 获取Json的方法类
        private static string BuildUploadObj(Context context)
        {
            // SaveDesigner为保存操作的设计组件，其他操作请查询T_MDL_FormOperationType 表格
            var designType = TypesContainer.GetOrRegister("Kingdee.BOS.Business.Bill.OperationService.SaveDesigner,Kingdee.BOS.Business.Bill");
            var designer = Activator.CreateInstance(designType) as OperationWebServiceDesigner;
            designer.OperationId = "Save";
            designer.IsWebApi = true;

            var meta = FormMetaDataCache.GetCachedFormMetaData(context, "RDLV_PendingCollectionList");
            var model = designer.CreateServiceModel(context, meta, null) as FormServiceModel;


            // WebApiParamHelper 为内部封装WebApi帮助类，没有对外发布，需要用发射调用获取JSON
            var webApiHelperClass =
                "Kingdee.BOS.Business.PlugIn.DynamicService.WebApiParamHelper,Kingdee.BOS.Business.PlugIn";
            var webApiHelperType = TypesContainer.GetOrRegister(webApiHelperClass);
            var webApiHelper = Activator.CreateInstance(webApiHelperType);
            var getJsonData = webApiHelperType.GetMethod("GetJSONData", new Type[] { typeof(DTOType), typeof(Boolean) });
            return getJsonData?.Invoke(webApiHelper, new object[] { model?.RequestDTOType, true }).GetString();
        }

    }
}
